package com.yf.zzmusic.exception;
import com.yf.zzmusic.common.Constants;
import com.yf.zzmusic.common.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 自定义异常类
 * 全局异常处理器
 */
@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result handle(ServiceException exception){
        return  Result.error(exception.getCode(),exception.getMessage());
    }

    /**
     * 处理请求参数格式错误异常
     *
     */
    @ExceptionHandler
    public Result handleBindException(BindException e){
        StringBuilder stringBuilder=new StringBuilder();
        List<FieldError> fieldErrors=e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            stringBuilder.append(fieldError.getDefaultMessage());
        }
        String message = "请求参数格式错误: "+stringBuilder.toString();
        return Result.error(Constants.REQUEST_BODY_ERROR, message);
    }

}
